package com.mspbots.rule.queue.producer;

import com.mspbots.api.service.MessagesService;
import com.mspbots.api.service.SystemConfigurationService;
import com.mspbots.api.service.TenantConfigurationService;
import com.mspbots.api.service.TenantService;
import com.mspbots.cw.request.MessagesDTO;
import com.mspbots.cw.request.TenantDTO;
import com.mspbots.dto.enums.Configuration;
import com.mspbots.rule.scheduled.service.MessagesSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mspbots.rule.config.RuleConfiguration.REDIS_KEY_PREFIX_SYSTEM;
import static com.mspbots.rule.config.RuleConfiguration.REDIS_KEY_PREFIX_TENANT;


/**
 * @ClassName com.mspbots.rule.queue.producer.ScheduledMessageProducer
 * @Description TODO
 * @Author Jun
 * @Date 2019/9/2 16:32
 * @Version 1.0
 **/
@Slf4j
@Service
public class ScheduledMessageProducer {

    static final String MESSAGES_SWITCH_ON = "on";
    @Autowired
    SystemConfigurationService systemConfigurationService;
    @Autowired
    TenantConfigurationService tenantConfigurationService;
    @Autowired
    TenantService tenantService;
    @Autowired
    MessagesService messagesService;
    @Autowired
    private RabbitMessagingTemplate messagingTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private MessagesSendService messagesSendService;


    private Map<String, Boolean> sendingMap = new HashMap<>();

    @Scheduled(cron = "0 0/1 * * * ?")
    public void sendToTeams() {
        List<MessagesDTO> messages = getMessageList("status");
        if (!CollectionUtils.isEmpty(messages)) {
            log.info("send List : {}", messages.size());
            messagesSendService.sendToTeams(messages);
            List<MessagesDTO> messagesForwards = messages.stream().filter(item -> "Ready".equals(item.getForwardStatus()))
                    .filter(item -> !StringUtils.isEmpty(item.getTeamsUserId())).collect(Collectors.toList());
            messagesSendService.sendForward(messagesForwards);
        } else {
            log.info("send List null");
        }

    }


    //    @Scheduled(cron="30 0/1 * * * ?")
    public void sendForward() {
        /*log.info("Scheduled Message forward...");
        List<MessagesDTO> messages = getMessageList("forwardStatus");
        if (!CollectionUtils.isEmpty(messages)) {
//            this.messagingTemplate.convertAndSend("msp.rule.ai", "schedule.send",  messages);
            messagesSendService.sendForward(messages);
        }
*/
//        String systemSwitch = stringRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX_SYSTEM + Configuration.MESSAGES_SWITCH.getKeyword());
//        log.info("systemSwitch : {}", systemSwitch);
//        if (systemSwitch == null || MESSAGES_SWITCH_ON.equalsIgnoreCase(systemSwitch)) {
//            Flux.just(redisTemplate.opsForList().range(REDIS_KEY_PREFIX_TENANT + "tenants",0,-1))
//                    .parallel()
//                    .doOnNext(tenant -> {
//                        String tenantSwitch = stringRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX_TENANT + tenant.getId() + ":" + Configuration.MESSAGES_SWITCH.getKeyword());
//                        log.info("tenant_{}_switch : {}", tenant.getId(), tenantSwitch);
//                    })












            /*List<TenantDTO> tenantDTOS = redisTemplate.opsForList().range(REDIS_KEY_PREFIX_TENANT + "tenants",0,-1);
            log.info("tenant_size : {}", tenantDTOS.size());
            List<TenantDTO> tenants = tenantDTOS.stream().filter(item -> item.getStatusId() == 1).collect(Collectors.toList());
            log.info("tenant_active : {}", tenants.size());
            for (TenantDTO tenant : tenants) {
                String tenantSwitch = stringRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX_TENANT + tenant.getId() + ":" + Configuration.MESSAGES_SWITCH.getKeyword());
                log.info("tenant_{}_switch : {}", tenant.getId(), tenantSwitch);
                if (tenantSwitch ==null || MESSAGES_SWITCH_ON.equalsIgnoreCase(tenantSwitch)) {
                    Map<String,Object> msgParams = Map.of("tenantId",tenant.getId(),type,"Ready", "expireDate",LocalDateTime.now());
                    List<MessagesDTO> tenantMsgList = messagesService.findList(msgParams);
                    if (!CollectionUtils.isEmpty(tenantMsgList)) {
                        log.info("tenant_{}_msg : {}", tenant.getId(), tenantMsgList.size());
                        for (MessagesDTO messagesDTO : tenantMsgList) {
                            String sending = stringRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX_TENANT + messagesDTO.getTenantId() + ":" + messagesDTO.getRuleId()+"_sending");

                            if (Boolean.valueOf(sending)) {
                                result.add(messagesDTO);
                            } else {
                                log.info("tenant_{}_rule_{}_{} ",messagesDTO.getTenantId(), messagesDTO.getRuleId(), sending);
                            }
                        }
                    }
                }
            }
        }*/

    }

    private List<MessagesDTO> getMessageList(String type) {
        List<MessagesDTO> result = new ArrayList<>();
        String systemSwitch = stringRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX_SYSTEM + Configuration.MESSAGES_SWITCH.getKeyword());
        log.info("systemSwitch : {}", systemSwitch);
        if (systemSwitch == null || MESSAGES_SWITCH_ON.equalsIgnoreCase(systemSwitch)) {
//            Map<String,Object> params = Map.of("statusId",1);
            List<TenantDTO> tenantDTOS = redisTemplate.opsForList().range(REDIS_KEY_PREFIX_TENANT + "tenants", 0, -1);
            log.info("tenant_size : {}", tenantDTOS.size());
            List<TenantDTO> tenants = tenantDTOS.stream().filter(item -> item.getStatusId() == 1).collect(Collectors.toList());
            log.info("tenant_active : {}", tenants.size());
            for (TenantDTO tenant : tenants) {
                String tenantSwitch = stringRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX_TENANT + tenant.getId() + ":" + Configuration.MESSAGES_SWITCH.getKeyword());
                log.info("tenant_{}_switch : {}", tenant.getId(), tenantSwitch);
                if (tenantSwitch == null || MESSAGES_SWITCH_ON.equalsIgnoreCase(tenantSwitch)) {
                    Map<String, Object> msgParams = Map.of("tenantId", tenant.getId(), type, "Ready", "expireDate", LocalDateTime.now());
                    List<MessagesDTO> tenantMsgList = messagesService.findList(msgParams);
                    if (!CollectionUtils.isEmpty(tenantMsgList)) {
                        log.info("tenant_{}_msg : {}", tenant.getId(), tenantMsgList.size());
                        for (MessagesDTO messagesDTO : tenantMsgList) {
                            String sending = stringRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX_TENANT + messagesDTO.getTenantId() + ":" + messagesDTO.getRuleId() + "_sending");

                            if (Boolean.valueOf(sending)) {
                                result.add(messagesDTO);
                            } else {
                                log.info("tenant_{}_rule_{}_{} ", messagesDTO.getTenantId(), messagesDTO.getRuleId(), sending);
                            }
                        }
                    }
                }
            }
        }
        return result;
    }


}
